#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from werkzeug.serving import make_server
import threading
from pathlib import Path
# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent.parent))
from common.config import WORK_PATH, SecurityConfig, ServiceConfig
from flask_cors import CORS
from flask import Flask, send_file, abort
from common.utils import LogUtil

logger = LogUtil.get_logger(__name__)

class ResourceService:
    """设备资源服务，使用Flask处理HTTP资源请求"""
    
    def __init__(self, host: str, port: int):
        self.host = host
        self.port = port
        self.debug = True
        self.use_reloader = False
        self.server = None
        self.thread = None
        self.static_root = WORK_PATH / 'resources'
        # 确保静态文件目录存在
        self.static_root.mkdir(exist_ok=True)
        self.app = self.__init_flask_app()
        # 设置路由
        self.__setup_routes()

    def __del__(self):
        """析构函数，关闭资源服务"""
        self.destroy()
    
    def destroy(self):
        """停止资源服务"""
        if self.server:
            logger.info("正在停止资源服务...")
            self.server.shutdown()
        if self.thread:
            self.thread.join()
        self.thread = None
        self.server = None
        self.app = None
        logger.info("资源服务已停止")

    def __init_flask_app(self):
        """初始化Flask应用

        Returns:
            Flask: Flask应用实例
        """
        # 创建Flask应用
        app = Flask(__name__, static_url_path='/', static_folder=self.static_root)
        # 启用CORS
        CORS(app)
        # 配置app
        app.logger = logger
        app.config['HOST'] = self.host
        app.config['PORT'] = self.port
        app.config['DEBUG'] = self.debug
        app.config['USE_RELOADER'] = self.use_reloader
        app.config['SECRET_KEY'] = SecurityConfig.SECRET_KEY
        return app

    def __setup_routes(self):
        """设置Flask路由"""
        @self.app.route('/health')
        def health_check():
            """健康检查端点"""
            return {}, 200
            
        @self.app.route('/<path:filepath>')
        def handle_request(filepath):
            """提供静态文件服务"""
            try:
                file_path = self.static_root / filepath
                # 安全检查：确保文件路径在静态目录内
                if not str(file_path.resolve()).startswith(str(self.static_root.resolve())):
                    logger.warning(f"尝试访问静态目录外的文件: {filepath}")
                    abort(403)
                # 检查文件是否存在
                if not file_path.exists() or not file_path.is_file():
                    logger.warning(f"请求的文件不存在: {filepath}")
                    abort(404)
                logger.info(f"提供静态文件: {filepath}")
                return send_file(file_path)
            except Exception as e:
                logger.error(f"提供静态文件时发生错误: {e}")
                abort(500)
    
    def start(self):
        """启动资源服务"""
        # 使用Werkzeug的make_server创建服务器
        self.server = make_server(self.host, self.port, self.app, threaded=True)
        self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
        self.thread.start()
        logger.info(f"资源服务启动成功：http://{self.host}:{self.port}")
    
    def is_alive(self) -> bool:
        """检查资源服务是否存活"""
        if self.thread is None:
            return False
        return self.thread.is_alive()